<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Map\Map;
use app\common\library\Wechat;
use app\common\manager\BaseManager;
use app\common\manager\CommentManager;
use app\common\manager\GroupManager;
use app\common\model\Region;
use think\Exception;

/**
 * 组队接口
 */
class Group extends Api
{
    protected $noNeedLogin = ['teamList','detail','teamJoiner','commentList'];
    protected $noNeedRight = ['*'];

    /**
     * 个人组队
     * @title string 组队标题
     * @is_store int 是否选择门店 1=是,0=否
     * @store_id int 门店id
     * @address string 地址
     * @start_date string 开始时间
     * @end_date string 结束时间
     * @number_people int 人数
     * @describe string 描述
     * @long float 经度
     * @lat float 纬度
     * @return void
     */
    public function team()
    {
        try {
            $title = $this->request->post('title');
            $is_store = $this->request->post('is_store') ?? 0;
            $store_id = $this->request->post('store_id') ?? 0;
            $address = $this->request->post('address') ?? '';
            $start_date = $this->request->post('start_date');
            $end_date = $this->request->post('end_date');
            $number_people = $this->request->post('number_people');
            $describe = $this->request->post('describe');
            $long = $this->request->post('long') ?? 0;
            $lat = $this->request->post('lat') ?? 0;
            $image = $this->request->post('image');
            $assistantIds = $this->request->post('assistantId') ?? '';
            $type = $this->request->post('type');
            $data = [
                'title'=>$title,
                'is_store'=>$is_store,
                'store_id'=>$store_id,
                'address'=>$address,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'number_people'=>$number_people,
                'describe'=>$describe,
                'long'=>$long,
                'lat'=>$lat,
                'image'=>$image,
                'assistant_ids' => $assistantIds,
            ];
            $addressConfig = get_addon_config('address');
            $map = new Map($addressConfig);
            $location = $lat.','.$long;
            $map->getInfoByLocation($location);
            $response = $map->getResponse();
            $response = json_decode($response, true);
            if (!empty($response) && isset($response['status']) && $response['status'] == 0 && !empty($response['result']) && !empty($response['result']['address_component'])) {
                $province = $response['result']['address_component']['province'] ?: '';
                $city = $response['result']['address_component']['city'] ?: '';
                $district = $response['result']['address_component']['district'] ?: '';
                $data['province'] = Region::where('name',$province)->value('city_code');
                $data['city'] = Region::where('name',$city)->value('city_code');
                $data['district'] = Region::where('name',$district)->value('city_code');
            }
            $data['type'] = $type;
            $groupValidate = new \app\api\validate\Group();
            if(!$groupValidate->check($data)){
                $this->error($groupValidate->getError());
            }

            $result  = GroupManager::CaptainTeam($this->user,$data);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

    }

    public function teamList(){
        $page = $this->request->post('page') ?? 1;
        $lng = $this->request->post('lng') ?? 0.00;
        $lat = $this->request->post('lat') ?? 0.00;
        $type = $this->request->post('type') ?? 1;
        $level = $this->request->post('level') ?? 0;
        $radius = $this->request->post('radius') ?? 100;
        $size = $this->request->post('size') ?? 20;
        if ($size < 1){
            $size = 20;
        }
        if ($size > 20){
            $size = 20;
        }
        if ($page < 1){
            $page = 1;
        }
        try {
            $result = GroupManager::TeamList($level,$lng,$lat,$radius,$type,$page,$size);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

    }

    /**
     * 组队详情
     * @return void
     */
    public function detail()
    {
        $id = $this->request->post('id');
        $long = $this->request->post('lng');
        $lat = $this->request->post('lat');
        try {
            $result = GroupManager::detail($this->user,$id,$long,$lat);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除组队信息
     * @return void
     */
    public function del()
    {
        $id = $this->request->post('id');
        try {
            $result = GroupManager::del($this->user,$id);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 组队报名人员
     * @id int 组队Id
     * @page int 页码
     * @return void
     */
    public function teamJoiner()
    {
        $id = $this->request->post('id');
        $page = $this->request->post('page');
        if ($page < 1){
            $page = 1;
        }
        try {
            $result = GroupManager::teamJoiner($this->user,$id,$page);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 组队评论
     * @param string comment 评论
     * @param string image 图片
     * @param int tid 组队id
     * @param int pid 父级id
     * @return void
     */
    public function comment()
    {
        try {
            $comment = $this->request->post('comment');
            $image = $this->request->post('image');
            $tid = $this->request->post('tid');
            $pid = $this->request->post('pid') ?? 0;
            $data = ['content'=>$comment,'image'=>$image,'t_id'=>$tid,'up_tuc_Id'=>$pid,'ct_date'=>time()];
            $result = CommentManager::CommentAboutTeam($this->user,$data);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除评论
     * @param int tid 评论id
     * @return void
     */
    public function delComment()
    {
        try {
            $tid = $this->request->post('tid');
            $result = CommentManager::delCommentAboutTeam($this->user,$tid);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 评论列表
     * @param int tid 组队id
     * @param int page 页码
     * @param int pid 父级评论id
     * @return void
     */
    public function commentList(){

        try {
            $page = $this->request->post('page');
            if ($page < 1){
                $page = 1;
            }
            $tid = $this->request->post('tid') ?? 1;
            $pid = $this->request->post('pid') ?? 0;
            $result = CommentManager::listAboutTeam($tid,$this->user_id,$pid,$page);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

    }

    /**
     * 取消组队
     * @return void
     */
    public function cancelGroup()
    {
        $id = $this->request->post('id');
        try {
            $result = GroupManager::cancelGroup($this->user,$id);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    public function invite()
    {
        $user = $this->user;
        $id = $this->request->post('id');
        try {
            $wechat = new Wechat();
            $page = config('wechat.team_invite_page');
            $scene = ['t'=>1,'i'=>$user->invite_code,'id'=>$id];
            $image = $result = $wechat->getUnlimited(http_build_query($scene),$page);
            $result = json_decode($result,true);
            if (json_last_error() == JSON_ERROR_NONE){
                if (isset($result['errcode']) && !empty($result['errcode'])){
                    throw new Exception($result['errmsg']);
                }
            }else{
                $this->success('获取成功',['image'=>base64_encode($image)]);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function confirm()
    {
        $id = $this->request->post('id');
        $user = $this->user;
        try {
            $result = GroupManager::confirmGroup($user,$id);
            if($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    public function teamStore()
    {
        try {
            $title = $this->request->post('title');
            $store_id = $this->request->post('store_id') ?? 0;
            $start_date = $this->request->post('start_date');
            $end_date = $this->request->post('end_date');
            $number_people = $this->request->post('number_people');
            $describe = $this->request->post('describe');
            $is_store = $this->request->post('is_store');
            $image = $this->request->post('image');
            $data = [
                'title'=>$title,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'number_people'=>$number_people,
                'is_store'=>$is_store,
                'describe'=>$describe,
                'store_id'=>$store_id,
                'image'=>$image
            ];
            $groupValidate = new \app\api\validate\Group();
            if(!$groupValidate->check($data)){
                $this->error($groupValidate->getError());
            }

            $result  = GroupManager::CaptainTeamByStore($this->user,$store_id,$data);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

    }

}
